package javax.per.toolkit.tools.msg;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;



public class FindMsg {

	private static class tmpStruct{
		int num;
		Element ele;
		public String toString(){
			return ele.asXML()+"";
		}
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.print("key word:");
		Scanner sca=new Scanner(System.in);
		String line=sca.nextLine();
		sca.close();
		sca=new Scanner(line);
		List<String> list=new ArrayList<String>();
		while(sca.hasNext()){
			list.add(sca.next());
		}
		sca.close();
		System.out.println();
		SAXReader reader=new SAXReader();
		Document doc = null;
		try {
			doc = reader.read(Msg.class.getResource("msg.xml"));
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		Element root=(Element) doc.selectSingleNode("//msgs");
		@SuppressWarnings("unchecked")
		List<Node> nos=root.selectNodes("msg");
		List<tmpStruct> result=new ArrayList<tmpStruct>();
		for(Node no:nos){
			if(no instanceof Element){
				Element ele=(Element)no;
				String key=ele.attributeValue("key");
				String value=ele.attributeValue("value");
				String remark=ele.attributeValue("remark");
				if(key==null||value==null)
					continue;
				int match=0;
				for(String s:list){
					if(key.toLowerCase().contains(s.trim().toLowerCase())){
						match++;
					}
					if(value.toLowerCase().contains(s.trim().toLowerCase())){
						match++;
					}
					if(remark!=null&&remark.toLowerCase().contains(s.trim().toLowerCase())){
						match++;
					}
				}
				if(match!=0){
					tmpStruct tmp=new tmpStruct();
					tmp.num=match;
					tmp.ele=ele;
					result.add(tmp);
				}
			}
		}
		
		Collections.sort(result, new Comparator<tmpStruct>(){
			@Override
			public int compare(tmpStruct arg0, tmpStruct arg1) {
				if(arg0.num>arg1.num)
					return -1;
				if(arg0.num<arg1.num)
					return 1;
				return 0;
			}
			
		});
		
		for(tmpStruct tmp:result){
			System.out.println(tmp);
		}
		
	}

}
